package org.jeecgframework.core.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;

/**   
 * @Title: Http工具类.java
 * @author hujl
 * @date 2016-5-28 下午12:34:01
 * @version 
 */
@SuppressWarnings("deprecation")
public class HttpUtil {
	protected static final Logger logger = Logger.getLogger(HttpUtil.class);
	private HttpUtil(){}
	
	/**
	 * 发送HTTP_GET请求
	 * @see 该方法会自动关闭连接,释放资源
	 * @param requestURL    请求地址(含参数)
	 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
	 * @return 远程主机响应正文
	 */
	public static String sendGetRequest(String reqURL, String decodeCharset){
		long responseLength = 0;       //响应长度
		String responseContent = null; //响应内容
		HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例
		HttpGet httpGet = new HttpGet(reqURL);           //创建org.apache.http.client.methods.HttpGet
		try{
			HttpResponse response = httpClient.execute(httpGet); //执行GET请求
			HttpEntity entity = response.getEntity();            //获取响应实体
			if(null != entity){
				responseLength = entity.getContentLength();
				responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
				EntityUtils.consume(entity); //Consume response content
			}
			System.out.println("请求地址: " + httpGet.getURI());
			System.out.println("响应状态: " + response.getStatusLine());
			System.out.println("响应长度: " + responseLength);
			System.out.println("响应内容: " + responseContent);
		}catch(ClientProtocolException e){
			logger.error("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
		}catch(ParseException e){
			logger.error(e.getMessage(), e);
		}catch(IOException e){
			logger.error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
		}finally{
			httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
		}
		return responseContent;
	}
	
	
	/**
	 * 发送HTTP_POST请求
	 * @see 该方法为<code>sendPostRequest(String,String,boolean,String,String)</code>的简化方法
	 * @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
	 * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
	 * @param isEncoder 用于指明请求数据是否需要UTF-8编码,true为需要
	 */
	public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder){
		return sendPostRequest(reqURL, sendData, isEncoder, null, null);
	}
	
	
	/**
	 * 发送HTTP_POST请求
	 * @see 该方法会自动关闭连接,释放资源
	 * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
	 * @param reqURL        请求地址
	 * @param sendData      请求参数,若有多个参数则应拼接成param11=value11¶m22=value22¶m33=value33的形式后,传入该参数中
	 * @param isEncoder     请求数据是否需要encodeCharset编码,true为需要
	 * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
	 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
	 * @return 远程主机响应正文
	 */
	public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder, String encodeCharset, String decodeCharset){
		String responseContent = null;
		HttpClient httpClient = new DefaultHttpClient();
		
		HttpPost httpPost = new HttpPost(reqURL);
		//httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
		httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
		try{
			if(isEncoder){
				List<NameValuePair> formParams = new ArrayList<NameValuePair>();
				for(String str : sendData.split("&")){
					formParams.add(new BasicNameValuePair(str.substring(0,str.indexOf("=")), str.substring(str.indexOf("=")+1)));
				}
				httpPost.setEntity(new StringEntity(URLEncodedUtils.format(formParams, encodeCharset==null ? "UTF-8" : encodeCharset)));
			}else{
				httpPost.setEntity(new StringEntity(sendData));
			}
			
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (null != entity) {
				responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
				EntityUtils.consume(entity);
			}
		}catch(Exception e){
			logger.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
		}finally{
			httpClient.getConnectionManager().shutdown();
		}
		return responseContent;
	}
	
	
	/**
	 * 发送HTTP_POST请求
	 * @see 该方法会自动关闭连接,释放资源
	 * @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
	 * @param reqURL        请求地址
	 * @param params        请求参数
	 * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
	 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
	 * @return 远程主机响应正文
	 */
	public static String sendPostRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){
		String responseContent = null;
		HttpClient httpClient = new DefaultHttpClient();
		
		HttpPost httpPost = new HttpPost(reqURL);
		List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列
		for(Map.Entry<String,String> entry : params.entrySet()){
			formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		try{
			httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset));
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (null != entity) {
				responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
				EntityUtils.consume(entity);
			}
		}catch(Exception e){
			logger.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
		}finally{
			httpClient.getConnectionManager().shutdown();
		}
		return responseContent;
	}
	
	/**
	 * 只有一个参数并无名称
	 * @Title: sendPostRequest
	 * @param reqURL
	 * @param param
	 * @param encodeCharset
	 * @param decodeCharset
	 * @return
	 * @return String
	 */
	public static String sendPostRequest(String reqURL, String param, String encodeCharset, String decodeCharset){
		String responseContent = null;
		HttpClient httpClient = new DefaultHttpClient();
		
		HttpPost httpPost = new HttpPost(reqURL);
		try{
			StringEntity myEntity = new StringEntity(param); 
			httpPost.addHeader("Content-Type", "text/xml"); 
			httpPost.setEntity(myEntity);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (null != entity) {
				responseContent = handleEntity(entity, decodeCharset)+"";
				EntityUtils.consume(entity);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
		}finally{
			httpClient.getConnectionManager().shutdown();
		}
		return responseContent;
	}
	
	public static Object handleEntity(HttpEntity entity, String charset)  
	        throws IOException {  
	    if (entity == null)  
	        return null;  
	  
	    ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
	    byte[] buffer = new byte[1024];  
	  
	    long count = entity.getContentLength();  
	    long curCount = 0;  
	    int len = -1;  
	    InputStream is = entity.getContent();  
	    while ((len = is.read(buffer)) != -1) {  
	        outStream.write(buffer, 0, len);  
	        curCount += len;  
	    }  
	  
	    byte[] data = outStream.toByteArray();  
	    outStream.close();  
	    is.close();  
	    return new String(data, charset);  
	}  
	
	/**
	 * 发送HTTPS_POST请求
	 * @see 该方法为<code>sendPostSSLRequest(String,Map<String,String>,String,String)</code>方法的简化方法
	 * @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
	 * @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
	 */
	public static String sendPostSSLRequest(String reqURL, Map<String, String> params){
		return sendPostSSLRequest(reqURL, params, null, null);
	}
	
	
	/**
	 * 发送HTTPS_POST请求
	 * @see 该方法会自动关闭连接,释放资源
	 * @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
	 * @param reqURL        请求地址
	 * @param params        请求参数
	 * @param encodeCharset 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
	 * @param decodeCharset 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
	 * @return 远程主机响应正文
	 */
	public static String sendPostSSLRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){
		String responseContent = "";
		HttpClient httpClient = new DefaultHttpClient();
		X509TrustManager xtm = new X509TrustManager(){
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			public X509Certificate[] getAcceptedIssuers() {return null;}
		};
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			ctx.init(null, new TrustManager[]{xtm}, null);
			SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
			httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
			
			HttpPost httpPost = new HttpPost(reqURL);
			List<NameValuePair> formParams = new ArrayList<NameValuePair>();
			for(Map.Entry<String,String> entry : params.entrySet()){
				formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? "UTF-8" : encodeCharset));
			
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (null != entity) {
				responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
				EntityUtils.consume(entity);
			}
		} catch (Exception e) {
			logger.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息为", e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return responseContent;
	}
	
	/**
	 * 发起https请求并获取结果
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param outputStr 提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		String retString ="";
		StringBuffer buffer = new StringBuffer();

		try {
			
			trustAllHttpsCertificates();  
			HostnameVerifier hv = new HostnameVerifier() {  
		        public boolean verify(String urlHostName, SSLSession session) {  
		            System.out.println("Warning: URL Host: " + urlHostName + " vs. "  
		                               + session.getPeerHost());  
		            return true;  
		        }  
		    }; 
		    HttpsURLConnection.setDefaultHostnameVerifier(hv);  
			URL url = new URL(null,requestUrl,new com.sun.net.ssl.internal.www.protocol.https.Handler());
			HttpURLConnection httpUrlConn =  (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();
			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();

			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			retString = buffer.toString();
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return retString;
	}
	
	/**
	 * 发送HTTP_POST请求
	 * @see 若发送的<code>params</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
	 * @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
	 * @param reqURL 请求地址
	 * @param params 发送到远程主机的正文数据,其数据类型为<code>java.util.Map<String, String></code>
	 * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
	 * @throws Exception 
	 */
	public static String sendPostRequestByJava(String reqURL, Map<String, String> params) throws Exception{
		StringBuilder sendData = new StringBuilder();
		for(Map.Entry<String, String> entry : params.entrySet()){
			sendData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
		}
		if(sendData.length() > 0){
			sendData.setLength(sendData.length() - 1); //删除最后一个&符号
		}
		return sendPostRequestByJava(reqURL, sendData.toString());
	}
	
	
	/**
	 * 发送HTTP_POST请求
	 * @see 若发送的<code>sendData</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
	 * @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
	 * @param reqURL   请求地址
	 * @param sendData 发送到远程主机的正文数据
	 * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
	 * @throws Exception 
	 */
	@SuppressWarnings("unused")
	public static String sendPostRequestByJava(String reqURL, String sendData) throws Exception{
		HttpURLConnection httpURLConnection = null;
		OutputStream out = null; //写
		BufferedReader reader = null;   //读
		int httpStatusCode = 0;  //远程主机响应的HTTP状态码
		/*******BCP接口监控*******/
		String bcp_intfCode = JSONObject.parseObject(sendData).get("SID").toString() ;//接口编码
		String bcp_reqUrl=reqURL;//请求地址
		long bcp_startTime = System.currentTimeMillis();//接口调用开始时间
		long bcp_endTime = 0;//接口调用结束时间
		String bcp_callParamText=sendData;//接口调用请求参数
		String bcp_resultContent = null;//接口调用返回参数
		/**********************/
		try{
			URL sendUrl = new URL(reqURL);
			httpURLConnection = (HttpURLConnection)sendUrl.openConnection();
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setDoOutput(true);        //指示应用程序要将数据写入URL连接,其值默认为false
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setConnectTimeout(60000); //30秒连接超时
			httpURLConnection.setReadTimeout(60000);    //30秒读取超时
			
			out = httpURLConnection.getOutputStream();
			out.write(sendData.toString().getBytes("UTF-8"));
			
			//清空缓冲区,发送数据
			out.flush();
			
			//获取HTTP状态码
			httpStatusCode = httpURLConnection.getResponseCode();
			
			
			//该方法只能获取到[HTTP/1.0 200 OK]中的[OK]
			//若对方响应的正文放在了返回报文的最后一行,则该方法获取不到正文,而只能获取到[OK],稍显遗憾
			//respData = httpURLConnection.getResponseMessage();
			
//			//处理返回结果
//			BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
//			String row = null;
//			String respData = "";
//			if((row=br.readLine()) != null){ //readLine()方法在读到换行[\n]或回车[\r]时,即认为该行已终止
//				respData = row;              //HTTP协议POST方式的最后一行数据为正文数据
//			}
//			br.close();
//			if(httpStatusCode!=200){
//				throw new ApplicationException("接口调用出错");
//			}
//			new InputStreamReader(in, cs).r
			if(httpStatusCode==200){
				reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));             
			}else{
				reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(),"UTF-8"));
			}
			String line = null;
			StringBuilder buffer = new StringBuilder();
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			/*******BCP接口监控*******/
			bcp_resultContent=buffer.toString();
			bcp_endTime = System.currentTimeMillis();
			/***********************/
			return buffer.toString();
		}catch(Exception e){
			/*******BCP接口监控*******/
			bcp_resultContent = "接口调用发生异常::"+e.getMessage();
			bcp_endTime = System.currentTimeMillis();
			/***********************/
			e.printStackTrace();
			logger.error("接口调用出错",e);
			throw new Exception("接口调用出错："+e.getMessage());
		}finally{
			if(out != null){
				try{
					out.close();
				}catch (Exception e){
					logger.error("关闭输出流时发生异常,堆栈信息如下", e);
				}
			}
			if(reader != null){
				try{
					reader.close();
				}catch(Exception e){
					logger.error("关闭输入流时发生异常,堆栈信息如下", e);
				}
			}
			if(httpURLConnection != null){
				httpURLConnection.disconnect();
				httpURLConnection = null;
			}
			
		}
	}
	
	public static String sendPostRequestPic(String url, String param) throws Exception{
		PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection conn = realUrl.openConnection();
                // 设置通用的请求属性
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent",
                                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(
                                new InputStreamReader(conn.getInputStream(),"UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                        result += line;
                }
        } catch (Exception e) {
                System.out.println("发送 POST 请求出现异常！" + e);
                e.printStackTrace();
                throw e;
        }
        // 使用finally块来关闭输出流、输入流
        finally {
                try {
                        if (out != null) {
                                out.close();
                        }
                        if (in != null) {
                                in.close();
                        }
                } catch (IOException ex) {
                        ex.printStackTrace();
                }
        }
        return result;
	}
	
	/**
	 * 发起https请求并获取结果
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param outputStr 提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static String httpRequestByProxy(String requestUrl, String outputStr, String proxyHost, int proxyPort) {
		String retString ="";
		StringBuffer buffer = new StringBuffer();

		try {
			URL url = new URL(requestUrl);
//			HttpURLConnection httpUrlConn =  (HttpURLConnection) url.openConnection();
			
			Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost , proxyPort));
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(proxy);
			
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod("POST");
			
			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();

			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			retString = buffer.toString();
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return retString;
	}
	
	public static String sendPostSSLRequest(String reqURL, String params, String encodeCharset, String decodeCharset){
		String responseContent = "";
		HttpClient httpClient = new DefaultHttpClient();
		X509TrustManager xtm = new X509TrustManager(){
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			public X509Certificate[] getAcceptedIssuers() {return null;}
		};
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			ctx.init(null, new TrustManager[]{xtm}, null);
			SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
			httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
			
			HttpPost httpPost = new HttpPost(reqURL);
			
			StringEntity myEntity = new StringEntity(params); 
			httpPost.setEntity(myEntity);
			
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (null != entity) {
				responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
				EntityUtils.consume(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息为", e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return responseContent;
	}
	
    private static void trustAllHttpsCertificates() throws Exception {  
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];  
        javax.net.ssl.TrustManager tm = new miTM();  
        trustAllCerts[0] = tm;  
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext  
                .getInstance("SSL");  
        sc.init(null, trustAllCerts, null);  
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc  
                .getSocketFactory());  
    }  
  
    static class miTM implements javax.net.ssl.TrustManager,  
            javax.net.ssl.X509TrustManager {  
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
            return null;  
        }  
  
        public boolean isServerTrusted(  
                java.security.cert.X509Certificate[] certs) {  
            return true;  
        }  
  
        public boolean isClientTrusted(  
                java.security.cert.X509Certificate[] certs) {  
            return true;  
        }  
  
        public void checkServerTrusted(  
                java.security.cert.X509Certificate[] certs, String authType)  
                throws java.security.cert.CertificateException {  
            return;  
        }  
  
        public void checkClientTrusted(  
                java.security.cert.X509Certificate[] certs, String authType)  
                throws java.security.cert.CertificateException {  
            return;  
        }  
    }
    
    /**
	 * 发送HTTP_POST请求
	 * @see 若发送的<code>sendData</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
	 * @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
	 * @param reqURL   请求地址
	 * @param sendData 发送到远程主机的正文数据
	 * @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
	 * @throws Exception 
	 */
	@SuppressWarnings("unused")
	public static String sendPostRequestSetTime(String reqURL, Map<String, String> params) throws Exception{
		HttpURLConnection httpURLConnection = null;
		OutputStream out = null; //写
		BufferedReader reader = null;   //读
		int httpStatusCode = 0;  //远程主机响应的HTTP状态码
		/*******BCP接口监控*******/
		String bcp_reqUrl=reqURL;//请求地址
		long bcp_startTime = System.currentTimeMillis();//接口调用开始时间
		long bcp_endTime = 0;//接口调用结束时间
		
		StringBuffer sendData = new StringBuffer("");
		for(Map.Entry<String, String> entry : params.entrySet()){
			sendData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
		}
		if(sendData.length() > 0){
			sendData.setLength(sendData.length() - 1); //删除最后一个&符号
		}
		
		String bcp_callParamText=sendData.toString();//接口调用请求参数
		String bcp_resultContent = null;//接口调用返回参数
		/**********************/
		try{
			URL sendUrl = new URL(reqURL);
			httpURLConnection = (HttpURLConnection)sendUrl.openConnection();
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setDoOutput(true);        //指示应用程序要将数据写入URL连接,其值默认为false
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setConnectTimeout(60000); //30秒连接超时
			httpURLConnection.setReadTimeout(60000);    //30秒读取超时
			
			out = httpURLConnection.getOutputStream();
			out.write(sendData.toString().getBytes("UTF-8"));
			
			//清空缓冲区,发送数据
			out.flush();
			
			//获取HTTP状态码
			httpStatusCode = httpURLConnection.getResponseCode();
			
			
			//该方法只能获取到[HTTP/1.0 200 OK]中的[OK]
			//若对方响应的正文放在了返回报文的最后一行,则该方法获取不到正文,而只能获取到[OK],稍显遗憾
			//respData = httpURLConnection.getResponseMessage();
			
//			//处理返回结果
//			BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
//			String row = null;
//			String respData = "";
//			if((row=br.readLine()) != null){ //readLine()方法在读到换行[\n]或回车[\r]时,即认为该行已终止
//				respData = row;              //HTTP协议POST方式的最后一行数据为正文数据
//			}
//			br.close();
//			if(httpStatusCode!=200){
//				throw new ApplicationException("接口调用出错");
//			}
//			new InputStreamReader(in, cs).r
			if(httpStatusCode==200){
				reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));             
			}else{
				reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(),"UTF-8"));
			}
			String line = null;
			StringBuilder buffer = new StringBuilder();
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			/*******BCP接口监控*******/
			bcp_resultContent=buffer.toString();
			bcp_endTime = System.currentTimeMillis();
			/***********************/
			return buffer.toString();
		}catch(Exception e){
			/*******BCP接口监控*******/
			bcp_resultContent = "接口调用发生异常::"+e.getMessage();
			bcp_endTime = System.currentTimeMillis();
			/***********************/
			e.printStackTrace();
			logger.error("接口调用出错",e);
			throw new Exception("接口调用出错："+e.getMessage());
		}finally{
			if(out != null){
				try{
					out.close();
				}catch (Exception e){
					logger.error("关闭输出流时发生异常,堆栈信息如下", e);
				}
			}
			if(reader != null){
				try{
					reader.close();
				}catch(Exception e){
					logger.error("关闭输入流时发生异常,堆栈信息如下", e);
				}
			}
			if(httpURLConnection != null){
				httpURLConnection.disconnect();
				httpURLConnection = null;
			}
			
		}
	}
	
	public static void main(String[] args) {
		String outStr = "<xml><appid>wx4798358a2a50a767</appid><mch_id>1358018002</mch_id><device_info>ios</device_info><nonce_str>8a9acfdc56466dec0156468f74c70004</nonce_str><sign>430B68D92E603D5B9B47CB8F6BDEEDC4</sign><body>zsins</body><detail></detail><attach>zsbx</attach><out_trade_no>2016080100000857</out_trade_no><fee_type>CNY</fee_type><total_fee>777738</total_fee><spbill_create_ip>124.160.88.197</spbill_create_ip><time_start>20160801224341</time_start><time_expire></time_expire><goods_tag>zsbx</goods_tag><notify_url>http://124.160.88.197:7001/mobile/allinpayCallback/notifySync.do</notify_url><trade_type>APP</trade_type><limit_pay></limit_pay></xml>";
		System.out.println(HttpUtil.sendPostSSLRequest("https://10.20.22.16/weixinPay", outStr,"UTF-8","UTF-8"));
//		System.out.println(HttpUtil.httpsRequest("https://10.20.22.16","POST", outStr));
//		System.out.println(HttpUtil.httpsRequest("http://10.20.22.16:18084", "POST", outStr));
	}
}
